<template>
  <div class="user-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">用户管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="Plus" size="large" @click="showAddDialog">
          添加用户
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选栏 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="用户名" label-width="70px">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入用户名"
            clearable
            size="default"
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="角色" label-width="50px">
          <el-select 
            v-model="searchForm.role" 
            placeholder="请选择角色"
            clearable
            size="default"
            style="width: 150px"
          >
            <el-option label="站点管理员" value="station_manager" />
            <el-option label="客户" value="customer" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" size="default" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" size="default" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        :data="groupedUserList" 
        style="width: 100%"
        v-loading="loading"
        row-key="id"
        stripe
      >
        <el-table-column prop="roleGroup" label="角色" width="120" align="center">
          <template #default="scope">
            <div v-if="scope.row.isGroupRow" class="group-header">
              <el-tag :type="getRoleType(scope.row.role)" size="large" effect="dark">
                {{ getRoleText(scope.row.role) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="145" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="!scope.row.isGroupRow" class="table-text">{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="realName" label="真实姓名" width="110" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="!scope.row.isGroupRow" class="table-text">{{ scope.row.realName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="135">
          <template #default="scope">
            <span v-if="!scope.row.isGroupRow" class="table-text">{{ scope.row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="380" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="!scope.row.isGroupRow" class="table-text">{{ scope.row.email }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" width="350" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="!scope.row.isGroupRow" class="table-text">{{ scope.row.address }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag v-if="!scope.row.isGroupRow" :type="scope.row.status === 'active' ? 'success' : 'info'" size="default">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <template v-if="!scope.row.isGroupRow">
              <el-button 
                type="primary" 
                size="default"
                link
                :icon="Edit"
                @click="editUser(scope.row)"
              >
                编辑
              </el-button>
              <el-button 
                :type="scope.row.status === 'active' ? 'warning' : 'success'"
                size="default"
                link
                @click="toggleUserStatus(scope.row)"
              >
                {{ scope.row.status === 'active' ? '禁用' : '启用' }}
              </el-button>
              <el-button 
                type="danger" 
                size="default"
                link
                :icon="Delete"
                @click="deleteUser(scope.row)"
              >
                删除
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogMode === 'add' ? '添加用户' : '编辑用户'"
      width="600px"
      @close="resetForm"
    >
      <el-form 
        ref="userFormRef"
        :model="userForm" 
        :rules="userRules" 
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="userForm.username" 
            placeholder="请输入用户名"
            :disabled="dialogMode === 'edit'"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="dialogMode === 'add'">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="站点管理员" value="station_manager" />
            <el-option label="客户" value="customer" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" maxlength="11" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="地址" prop="address">
          <el-input 
            v-model="userForm.address" 
            type="textarea" 
            placeholder="请输入地址"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser" :loading="submitting">
            {{ dialogMode === 'add' ? '添加' : '保存' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { usersAPI } from '@/api'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogMode = ref('add') // 'add' | 'edit'
const submitting = ref(false)
const userFormRef = ref()

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  username: '',
  role: null
})

// 用户表单
const userForm = reactive({
  id: null,
  username: '',
  password: '',
  realName: '',
  role: null,
  phone: '',
  email: '',
  address: '',
  status: 'active'
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度为3-50个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, 
      message: '邮箱格式不正确', 
      trigger: 'blur' 
    },
    { 
      max: 100, 
      message: '邮箱长度不能超过100个字符', 
      trigger: 'blur' 
    }
  ]
}

// 用户列表数据
const userList = ref([])

// 过滤后的用户列表（不显示管理员）
const filteredUserList = computed(() => {
  return userList.value.filter(user => user.role !== 'admin')
})

// 按角色分组的用户列表
const groupedUserList = computed(() => {
  const filtered = filteredUserList.value
  const groups = {}
  
  // 按角色分组
  filtered.forEach(user => {
    if (!groups[user.role]) {
      groups[user.role] = []
    }
    groups[user.role].push(user)
  })
  
  // 组装成带分组头的列表
  const result = []
  const roleOrder = ['station_manager', 'customer'] // 角色显示顺序
  
  roleOrder.forEach(role => {
    if (groups[role] && groups[role].length > 0) {
      // 添加分组头
      result.push({
        id: `group-${role}`,
        role: role,
        isGroupRow: true
      })
      // 添加该组的用户
      result.push(...groups[role])
    }
  })
  
  return result
})

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    
    const data = await usersAPI.getUsers(params)
    
    if (data) {
      userList.value = data.list || []
      total.value = data.total || 0
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 方法
const getRoleType = (role) => {
  const types = {
    admin: 'danger',
    station_manager: 'warning',
    customer: ''
  }
  return types[role] || 'info'
}

const getRoleText = (role) => {
  const texts = {
    admin: '管理员',
    station_manager: '站点管理员',
    customer: '客户'
  }
  return texts[role] || '未知'
}

const showAddDialog = () => {
  dialogMode.value = 'add'
  dialogVisible.value = true
}

const editUser = (user) => {
  dialogMode.value = 'edit'
  Object.assign(userForm, { ...user })
  dialogVisible.value = true
}

const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  Object.assign(userForm, {
    id: null,
    username: '',
    password: '',
    realName: '',
    role: null,
    phone: '',
    email: '',
    address: '',
    status: 'active'
  })
}

const saveUser = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    submitting.value = true
    
    if (dialogMode.value === 'add') {
      // 添加用户
      await usersAPI.createUser(userForm)
      ElMessage.success('用户添加成功')
    } else {
      // 编辑用户
      await usersAPI.updateUser(userForm.id, userForm)
      ElMessage.success('用户更新成功')
    }
    
    dialogVisible.value = false
    fetchUserList()
  } catch (error) {
    console.error('保存用户失败:', error)
    if (error.errors) {
      // 验证失败
      return
    }
    ElMessage.error(error.message || '保存失败')
  } finally {
    submitting.value = false
  }
}

const toggleUserStatus = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要${user.status === 'active' ? '禁用' : '启用'}用户 ${user.realName} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await usersAPI.toggleUserStatus(user.id)
    ElMessage.success(`用户已${user.status === 'active' ? '禁用' : '启用'}`)
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换用户状态失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${user.realName} 吗？此操作不可恢复！`,
      '危险操作',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    await usersAPI.deleteUser(user.id)
    ElMessage.success('用户删除成功')
    
    // 如果当前页没有数据了，回到上一页
    if (userList.value.length === 1 && currentPage.value > 1) {
      currentPage.value--
    }
    fetchUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    username: '',
    role: null
  })
  handleSearch()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchUserList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchUserList()
}

// 初始化
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.filter-card {
  margin-bottom: 12px;
  border-radius: 8px;
}

:deep(.filter-card .el-card__body) {
  padding: 16px 20px;
}

.search-form {
  margin-bottom: 0;
}

:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  margin-right: 16px;
}

:deep(.search-form .el-form-item__label) {
  font-size: 15px;
  color: #606266;
  font-weight: 500;
}

:deep(.search-form .el-input__inner) {
  font-size: 15px;
}

:deep(.search-form .el-button) {
  font-size: 15px;
  padding: 9px 18px;
}

.table-card {
  border-radius: 8px;
}

:deep(.table-card .el-card__body) {
  padding: 0;
}

:deep(.el-table) {
  font-size: 15px;
}

:deep(.el-table th.el-table__cell) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
  font-size: 15px;
  padding: 14px 0;
}

:deep(.el-table td.el-table__cell) {
  padding: 14px 0;
}

.table-text {
  font-size: 15px;
  color: #303133;
}

:deep(.el-table .el-button) {
  font-size: 15px;
  padding: 6px 10px;
  margin: 0 2px;
}

:deep(.el-table .el-tag) {
  font-size: 14px;
  padding: 4px 10px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding: 16px 20px;
}

:deep(.el-pagination) {
  font-size: 15px;
}

:deep(.el-pagination .el-pager li) {
  font-size: 15px;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
}

.dialog-footer {
  text-align: right;
}

/* 分组样式 */
.group-header {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 16px;
  font-weight: 600;
  font-size: 16px;
}

:deep(.el-table__row) {
  transition: all 0.2s;
}

/* 分组行样式 */
:deep(.el-table__row:has(.group-header)) {
  background: linear-gradient(to right, #f5f7fa 0%, #ffffff 100%) !important;
}

:deep(.el-table__row:has(.group-header) td) {
  border-bottom: 2px solid #e4e7ed !important;
  padding: 4px 0 !important;
}

:deep(.el-table__row:has(.group-header):hover) {
  background: linear-gradient(to right, #f5f7fa 0%, #ffffff 100%) !important;
}

/* 分组行后的第一个用户行 */
:deep(.el-table__row:has(.group-header) + .el-table__row) {
  border-top: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form :deep(.el-form-item) {
    margin-right: 0;
    margin-bottom: 12px;
  }

  .pagination {
    justify-content: center;
  }
}
</style>
